package com.zuxia.filter;

import com.google.gson.JsonObject;
import com.zuxia.entity.JwtInfo;
import com.zuxia.utils.JwtUtils;
import com.zuxia.utils.RedisTokenUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    @Resource
    private RedisTokenUtil redisTokenUtil;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();

        String path = request.getURI().getPath();
        if(path.contains("/token")){
            String token="";
            JwtInfo jwtInfo = new JwtInfo();
            String accessToken = request.getHeaders().getFirst("Authorization");
            if(accessToken==null||accessToken.isEmpty()){
                return out(exchange.getResponse(),"请传递签名");
            }
            try {
                JwtUtils.checkJwtTToken(accessToken);
            }catch (Exception e){
                String refreshToken = redisTokenUtil.getToken(accessToken);
                if(refreshToken==null||"".equals(refreshToken)){
                    return out(exchange.getResponse(),"token无效或过期，请重新登陆");
                }
                jwtInfo = JwtUtils.getMemberIdByJwtToken(refreshToken);
                String newAccessToken = JwtUtils.getJwtToken(jwtInfo, 24*60*60 * 1000L);
                System.out.println("newAccessToken:"+newAccessToken);
                redisTokenUtil.setNewToken(newAccessToken);
                redisTokenUtil.changeToken(accessToken,newAccessToken,refreshToken);
                token=newAccessToken;
            }

            if(path.contains("/admin")){
                if(jwtInfo.getRoleId()!=1){
                    return out(exchange.getResponse(),"权限不足");
                }
            }else if(path.contains("/merchant")){
                if(jwtInfo.getRoleId()!=2&&jwtInfo.getRoleId()!=1){
                    return out(exchange.getResponse(),"权限不足");
                }
            }
            if(token!=null||!token.isEmpty()){
                exchange.getResponse().getHeaders().add("Authorization","Bearer "+ token);
            }
            return chain.filter(exchange.mutate().build());
        }


        System.out.println(path);
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    //使用webflux输入请求信息
    private Mono<Void> out(ServerHttpResponse response) {

        JsonObject message = new JsonObject();
        message.addProperty("success", false);
        message.addProperty("code", 28004);
        message.addProperty("data", "");
        message.addProperty("message", "鉴权失败");
        byte[] bytes = message.toString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        //输出http响应
        return response.writeWith(Mono.just(buffer));
    }

    //使用webflux输入请求信息
    private Mono<Void> out(ServerHttpResponse response,String value) {

        JsonObject message = new JsonObject();
        message.addProperty("success", false);
        message.addProperty("code", 28003);
        message.addProperty("data", "");
        message.addProperty("message", value);
        byte[] bytes = message.toString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        //输出http响应
        return response.writeWith(Mono.just(buffer));
    }
}
